// Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.

// 委托数据表定义
package db

import (
	"github.com/pkg/errors"
	"scase.io/application-auto-scaling-service/pkg/setting"
	"scase.io/application-auto-scaling-service/pkg/utils/security"
)

type AgencyInfo struct {
	OriProjectId    string `orm:"column(ori_project_id);size(64);pk" json:"ori_project_id"`
	ProjectId       string `orm:"column(project_id);size(64)" json:"project_id"`
	AccessKey       string `orm:"column(access_key);size(1024)" json:"access_key"`
	SecretAccessKey string `orm:"column(secret_access_key);size(1024)" json:"secret_access_key"`
	TimeModel
}

// AddOrUpdateAgencyInfo add or update AgencyInfo
func AddOrUpdateAgencyInfo(info *AgencyInfo) error {
	if info == nil || info.ProjectId == "" {
		return errors.Errorf("func AddOrUpdateAgencyInfo[%+v] has invalid args", info)
	}

	info.IsDeleted = notDeletedFlag
	_, err := ormer.InsertOrUpdate(info)
	if err != nil {
		return errors.Wrapf(err, "add or update agency info[%s] err", info.ProjectId)
	}
	return nil
}

// GetAgencyInfo get AgencyInfo
func GetAgencyInfo(oriProjectId string) (*AgencyInfo, error) {
	g := &AgencyInfo{OriProjectId: oriProjectId}
	if err := ormer.Read(g); err != nil {
		return nil, errors.Wrapf(err, "read agency info[ori_project_id: %s] from db err", oriProjectId)
	}
	accessKey, err := security.GCM_Decrypt(g.AccessKey, setting.GCMKey, setting.GCMNonce)
	if err != nil {
		return nil, errors.Wrapf(err, "decrypt ak error for %v", err)
	}
	secretAccessKey, err := security.GCM_Decrypt(g.SecretAccessKey, setting.GCMKey, setting.GCMNonce)
	if err != nil {
		return nil, errors.Wrapf(err, "decrypt ak error for %v", err)
	}
	g.AccessKey = accessKey
	g.SecretAccessKey = secretAccessKey
	return g, nil
}
